package com.onion.utils.utils;

import com.onion.utils.support.exception.OnionException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {

    /**
     * 字符串转日期
     * @param strDate
     * @param formatter
     * @return
     */
    public static Date getDate(String strDate, String formatter){
        SimpleDateFormat sdf = new SimpleDateFormat(formatter);
        try {
            return sdf.parse(strDate);
        } catch (ParseException exp) {
            throw new OnionException(-1, "日期格式转换出错：" + strDate + ", Error=" + exp.getMessage());
        }
    }

    /**
     * 日期格式化
     * @param date
     * @param formatter
     * @return
     */
    public static String format(Date date, String formatter){
        SimpleDateFormat sdf = new SimpleDateFormat(formatter);
        return sdf.format(date);
    }

    /**
     * 当天开始时间
     * @param date
     * @return
     */
    public static Date getDayStart(Date date){
        String strDay = format(date, "yyyy-MM-dd");
        return getDate(strDay, "yyyy-MM-dd");
    }

    public static Date getDayEnd(Date date){
        String strDay = format(date, "yyyy-MM-dd") + " 23:59:59 999";
        return getDate(strDay, "yyyy-MM-dd HH:mm:ss SSS");
    }

    /**
     * 获取当月第一天
     * @param date
     * @return
     */
    public static Date getMonthStart(Date date){
        String strMonthStart = format(date, "yyyy-MM") + "-01";
        return getDate(strMonthStart, "yyyy-MM-dd");
    }

    /**
     * 获取当月最后一天23:59:59 999
     * @param date
     * @return
     */
    public static Date getMonthEnd(Date date){
        Date monthStartDate = getMonthStart(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(monthStartDate);
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.MILLISECOND, -1);
        return calendar.getTime();
    }

    /**
     * 日期加减
     * @param date
     * @param days
     * @return
     */
    public static Date dateAdd(Date date, int days){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, days);
        return calendar.getTime();
    }

    /**
     * 月份加减
     * @param date
     * @param months
     * @return
     */
    public static Date monthAdd(Date date, int months){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, months);
        return calendar.getTime();
    }

    public static void main(String[] args){
        Date now = new Date();
        System.out.println(format(now, "yyyy-MM-dd"));
        System.out.println(getDayStart(now));
        System.out.println(getDayEnd(now));
        System.out.println(getMonthStart(now));
        System.out.println(getMonthEnd(now));
    }

}